package com.example.a16021.myapplication;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MobileLocationActivity extends AppCompatActivity {
    EditText et_mobile;
    Button button;
    TextView tv_loaction;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mobile_location);

        et_mobile= (EditText) findViewById(R.id.et_mobile);
        tv_loaction= (TextView) findViewById(R.id.tv_loaction);

        button=  findViewById(R.id.btn_query);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MobileAsyncTask mobileAsyncTask=new MobileAsyncTask();
                mobileAsyncTask.execute();
            }
        });
    }
    class MobileAsyncTask extends AsyncTask<String,Integer,String>{
        @Override
        protected String doInBackground(String... strings) {
            String mobile=et_mobile.getText().toString();
            String path = "http://v.juhe.cn/xhzd/query?key="
                    +mobile+"&key=e100ab9b5194e04ef6e4dd67b8f15520";
            try {
                URL url=new URL(path);
                HttpURLConnection connection= (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setReadTimeout(5000);
                connection.setConnectTimeout(5000);

                connection.connect();
                int code=connection.getResponseCode();
                if(code==200){
                    InputStream inputStream=connection.getInputStream();
                    byte[] bytes=new byte[1024];
                    int len=0;
                    ByteArrayOutputStream bos=new ByteArrayOutputStream();
                    while ((len=inputStream.read(bytes))!=-1){
                        bos.write(bytes,0,len);
                    }
                    String s=new String(bos.toByteArray());
                    System.out.println(s);
                    JSONObject jo=new JSONObject(s);
                    JSONObject resultJo=jo.optJSONObject("result");
                    String zi=resultJo.optString("zi");
                    String py=resultJo.optString("py");
                    tv_loaction.setText(zi+py);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

    }
}
